<template>
    <div class="plan_list">
      <a-card>
        <!-- 创建按钮 -->
        <a-row type="flex" class="search_form">
          <div class="flex_item">
            <div class="flex_label">计划类型</div>
            <a-select @change="handlerQuery" v-model="type" style="flex: 1;" placeholder="不限">
              <a-select-option value="">不限</a-select-option>
              <a-select-option :value="0">完成A</a-select-option>
              <a-select-option :value="1">完成A未完成B</a-select-option>
            </a-select>
          </div>
          <div class="flex_item">
            <div class="flex_label">创建人</div>
            <a-select @change="handlerQuery" v-model="createdBy" style="flex: 1" placeholder="不限">
              <a-select-option value="">不限</a-select-option>
            </a-select>
          </div>
          <div style="flex: 1;"></div>
          <a-column :span="6">
            <a-input @change="handlerQuery" v-model="idOrName" placeholder="搜索计划名称或ID"><a-icon slot="prefix" type="search" /></a-input>
          </a-column>
          <a-column :span="6">
            <a-button style="margin-left: 12px;" @click="onAddPlan" type="primary"><a-icon type="plus" />创建计划</a-button>
          </a-column>
        </a-row>
        <!-- 表格 -->
        <div>
          <!-- <CountPlan /> -->
          <a-table 
            :columns="columns" 
            :data-source="planList" 
            :pagination="currentConfig"
            :loading="table_loading"
            @change="onTableHandle"
            :scroll="{x: true}"
            rowKey="id"
            style="margin-top:24px;"
          >
            <span slot="convertedRate" slot-scope="totalReport">
              <div v-if="totalReport.convertedRate" class="report">{{ totalReport.convertedRate }}%</div>
              <div v-else>暂无数据</div>
            </span>
            <span slot="chart" slot-scope="row">
              <div v-if="row.latestReport && row.latestReport.triggeredCount">
                <div>
                  <div>{{row.latestReport.lastMsgSendDay}}</div>
                  <div class="report">
                    <div><span>{{row.latestReport.triggeredCount}}</span>人次</div>
                    <div class="circle_container">
                      <div class="circle_content">
                        <div :style="getRotate(row.latestReport.convertedRate, true)" class="circle_bar"></div>
                        <div :style="getRotate(row.latestReport.convertedRate)" v-if="row.latestReport.convertedRate > 50" class="circle_bar"></div>
                      </div>
                    </div>
                    <div>{{row.latestReport.convertedRate || 0}}%</div>
                  </div>
                </div>
              </div>
              <div v-else>暂无数据</div>
            </span>
            <span slot="namestate" slot-scope="row">
              <div class="namestate" @click="handlerView(row)">
                <a-tooltip>
                  <template slot="title">
                    <span>进行中</span>
                  </template>
                  <a-icon type="check-circle" v-if="row.status === 2" style="color: #4c84ff;" theme="filled" /><!--进行中-->
                </a-tooltip>
                <a-tooltip>
                  <template slot="title">
                    <span>暂停</span>
                  </template>
                  <a-icon type="pause-circle" v-if="row.status === 3" theme="filled" style="color: #ffb64c;" /><!--暂停-->
                </a-tooltip>
                <a-tooltip>
                  <template slot="title">
                    <span>待审批</span>
                  </template>
                  <a-icon type="hourglass" v-if="row.status === 1" theme="filled" style="color: #15c96d;" /><!--待审批-->
                </a-tooltip>
                <a-tooltip>
                  <template slot="title">
                    <span>已结束</span>
                  </template>
                  <a-icon type="minus-circle" v-if="row.status === 4" style="color: #8492a6;" theme="filled" /><!--已结束-->
                </a-tooltip>
                <a-tooltip>
                  <template slot="title">
                    <span>已归档</span>
                  </template>
                  <a-icon type="minus-circle" v-if="row.status === 5" style="color: #8492a6;" theme="filled" /><!--已结束-->
                </a-tooltip>
                <a-tooltip>
                  <template slot="title">
                    <span>草稿</span>
                  </template>
                  <a-icon type="file-text" v-if="row.status === 0" style="color: #52bad3;" /><!--草稿-->
                </a-tooltip>
                <div>{{row.name}}</div>
              </div>
              <div>{{row.scheduleStart}} ~ {{row.scheduleEnd}}</div>
            </span>
            <span slot="type" slot-scope="row">
              <div v-if="row.type === 0">
                <div><a-icon type="thunderbolt" theme="filled" />触发 - 完成A</div>
                <DelayColView :delay-str="row.triggerRule" />
              </div>
              <div v-else>
                <div><a-icon type="thunderbolt" theme="filled" />触发 - 完成A未完成B</div>
                <DelayColView :delay-str="row.triggerRule" />
              </div>
            </span>
            <span slot="action" slot-scope="row">
              <a-space>
                <a v-if="row.status === 0" @click="onEdit(row)">编辑</a>
                <a v-if="row.status === 1" @click="onAudit(row)" v-action:audit="'push'">审批</a>
                <a v-if="row.status === 0 || row.status === 3" @click="onPublish(row)">发布</a>
                <a v-if="row.status === 2" @click="onPause(row)">暂停</a>
                <a v-if="row.status === 4" @click="onFile(row)">归档</a>
                <a @click="onDelete(row)">删除</a>
              </a-space>
            </span>
          </a-table>
        </div>
      </a-card>
    </div>
  </template>
  
  <script>
  import { mapActions, mapState } from 'vuex';
  import { baseMixin } from '@/store/app-mixin';
  import AddAndUpdatePlan from './addAndUpdatePlan';
  // import CountPlan from './countPlan';
  import DelayColView from './delayColView';
  const columns = [
          { 
            title: '计划id', 
            dataIndex: 'id', 
          },
          { 
            title: '状态/名称/起止日期', 
            scopedSlots: { customRender: 'namestate' },
          },
          { 
            title: '类型', 
            scopedSlots: { customRender: 'type' },
          },
          { 
            title: '最近一次（天）计划触发/目标完成率', 
            scopedSlots: { customRender: 'chart' },
          },
          { 
            title: '整体目标完成率', 
            dataIndex: 'totalReport',
            scopedSlots: { customRender: 'convertedRate' },
          },
          {
            title: '操作',
            fixed: 'right',
            width: 160,
            scopedSlots: { customRender: 'action' }
          }
        ]
  
    export default {
      name: 'PlanList',
      mixins: [baseMixin],
      components: {
        AddAndUpdatePlan,
        DelayColView
      },
      data () {
        return {
          columns,
          table_loading: false,
          planList: [],
          type: '',
          idOrName: '',
          createdBy: '',
          currentConfig: {
            current : 1,
            pageSize: 10,
            total: 0,
            pageSizeOptions: ['10', '20', '50', '100'],
            showQuickJumper: true,
            showSizeChanger: true,
            showTotal: (total) => {
              let pageConfig = this.currentConfig
              return `共 ${total} 条记录 第${pageConfig.current} / ${Math.ceil(total/pageConfig.pageSize)} 页`
            }
          },
        }
      },
      computed: {
        ...mapState('projectManage',['projectId']),
      },
      mounted () {
        this.onLoadPlanConfig();
      },
      watch: {
        projectId: function (val) {
          this.getList();
        }
      },
      methods: {
        ...mapActions('planManage', ['getAllPlanList', 'deletePlan', 'executePlanAction']),
        ...mapActions('projectManage', ['getProjectList', 'getEventList', 'getUserProperties']),
        onTreeSelect () {},
        getRotate(rate = 0, isFirst) {
          let transform = 'rotate(' + rate * 3.6 + 'deg)';
          if (isFirst && rate > 50) {
            transform = 'rotate(180deg)';
          }

          return {
            transform,
          }
        },
        // 创建
        onAddPlan () {
          this.$router.push('/operationPlanManage/add?projectId=' + this.projectId);
        },
        // 分页-每页条数
        onTableHandle (page) {
          this.currentConfig.current = page.current;
          this.currentConfig.pageSize = page.pageSize;
          this.getList();
        },
        handlerView(row) {
          this.$router.push('/operationPlanManage/view?id=' + row.id + '&projectId=' + this.projectId);
        },
        onEdit(row) {
          this.$router.push('/operationPlanManage/edit?id=' + row.id + '&projectId=' + this.projectId);
        },
        onPause(row) {
          this.$confirm({
            title: '暂停提示',
            content: '确认暂停吗',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              this.executePlanAction({ id: row.id, projectId: this.projectId, actionType: 'SUSPEND' })
              .then(()=>{
                this.$message.success('暂停成功');
                this.getList();
              })
              .catch((err) => this.$message.error('暂停失败，原因：' + err.msg + '！'))
            },
            onCancel: () => {},
          });
        },
        onPublish(row) {
          this.$confirm({
            title: '发布提示',
            content: '确认发布吗',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              this.executePlanAction({ id: row.id, projectId: this.projectId, actionType: 'SUBMIT', remark: '' })
              .then(()=>{
                this.$message.success('发布成功');
                this.getList();
              })
              .catch((err) => this.$message.error('发布失败，原因：' + err.msg + '！'))
            },
            onCancel: () => {},
          });
        },
        onFile(row) {
          this.$confirm({
            title: '存档提示',
            content: '确认存档吗',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              this.executePlanAction({ id: row.id, projectId: this.projectId, actionType: 'ARCHIVE' })
              .then(()=>{
                this.$message.success('存档成功');
                this.getList();
              })
              .catch((err) => this.$message.error('存档失败，原因：' + err.msg + '！'))
            },
            onCancel: () => {},
          });
        },
        onAudit(row) {
          this.$router.push('/operationPlanManage/audit?id=' + row.id + '&projectId=' + this.projectId);
        },
        handlerQuery() {
          this.getList();
        },
        // 获取删除行
        onDelete (row) {
          this.$confirm({
            title: '删除提示',
            content: '删除后无法恢复，您确定要继续吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              this.deletePlan({ planId: row.id, projectId: this.projectId })
              .then(()=>{
                this.$message.success('删除成功');
                this.getList();
              })
              .catch((err) => this.$message.error('删除失败，原因：' + err.msg + '！'))
            },
            onCancel: () => {},
          });
        },
        getList() {
          this.table_loading = true;
          const queryParams = {
            projectId: this.projectId, 
            type: this.type, 
            createdBy: this.createdBy, 
            idOrName: this.idOrName,
            pageSize: this.currentConfig.pageSize,
            page: this.currentConfig.current,
          };
          this.getAllPlanList(queryParams)
            .then(res => {
              this.planList = res.data.data || [];
              this.currentConfig.total = res.data.total;
              this.table_loading = false;
            }, () => {
              this.table_loading = false;
            });
        },
        // 初始化加载页面数据
        onLoadPlanConfig () {
          this.table_loading = true;
          this.getList();
        },
      }
    }
  </script>
  
  <style scoped>
  .plan_list {
    width: 100%;
  }

  .search_form .ant-form-item {
    display: flex;
  }

  .flex_item {
    width: 300px;
    display: flex;
  }

  .flex_label {
    line-height: 32px;
    padding: 0 10px;
  }

  .namestate {
    display: flex;
    align-items: center;
    cursor: pointer;
  }

  .namestate .anticon {
    margin-right: 6px;
  }

  .circle_container {
    position: relative;
    display: inline-block;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #e9eef2;
    margin: 0 4px 0 20px;
    vertical-align: text-bottom;
  }

  .circle_container::after {
    position: absolute;
    top: 2px;
    left: 2px;
    display: block;
    content: " ";
    border-radius: 50%;
    background-color: #fff;
    width: 16px;
    height: 16px;
    transition-property: all;
    transition-duration: .2s;
    transition-timing-function: ease-in;
  }

  .circle_content {
    position: absolute;
    width: 20px;
    height: 20px;
    clip: rect(0px,20px,20px,10px);
  }

  .circle_bar {
    transform: rotate(90deg);
    position: absolute;
    border: 2px solid #04CC61;
    width: 20px;
    height: 20px;
    clip: rect(0px,10px,20px,0px);
    border-radius: 50%;
  }

  .report {
    display: flex;
    margin-top: 10px;
  }
  </style>